package com.anivia.common.web.config.mybatisPlus.typeHandler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * List<Integer>转字符串
 *
 * @author wangj
 */
@MappedTypes(List.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class IntListToStringTypeHandler implements TypeHandler<List<Integer>> {

    public void setParameter(PreparedStatement preparedStatement, int i, List<Integer> list, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, CollUtil.join(list, ","));
    }

    @Override
    public List<Integer> getResult(ResultSet resultSet, String s) throws SQLException {
        String resultString = resultSet.getString(s);
        return handler(resultString);
    }

    @Override
    public List<Integer> getResult(ResultSet resultSet, int i) throws SQLException {
        String resultString = resultSet.getString(i);
        return handler(resultString);
    }

    @Override
    public List<Integer> getResult(CallableStatement callableStatement, int i) throws SQLException {
        String resultString = callableStatement.getString(i);
        return handler(resultString);
    }

    private List<Integer> handler(String resultString) {
        if (StringUtils.isNotBlank(resultString)) {
            return Arrays.stream(resultString.split(",")).map(Convert::toInt).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }
}


